package com.bsoft.hospitalchs.ui.childpicture;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;

import com.bsoft.hospitalchs.R;
import com.bsoft.hospitalchs.base.BaseFragment;
import com.bsoft.hospitalchs.common.MyApplication;
import com.bsoft.hospitalchs.model.ImageBean;
import com.bsoft.hospitalchs.model.PhotoResBean;
import com.bsoft.hospitalchs.model.PicResBean;
import com.bsoft.hospitalchs.model.PicSaveInfoBean;
import com.bsoft.hospitalchs.model.RecordInfo;
import com.bsoft.hospitalchs.model.SearchResBean;
import com.bsoft.hospitalchs.ui.childpicture.croupimage.CropImageUtils;
import com.bsoft.hospitalchs.ui.childpicture.croupimage.Loader;
import com.bsoft.hospitalchs.utils.SpUtils;
import com.bsoft.hospitalchs.utils.ToastUtils;
import com.bsoft.hospitalchs.widget.CustomProgress;
import com.bsoft.hospitalchs.widget.TakePhotosDialog;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionListener;
import com.yzs.imageshowpickerview.ImageShowPickerBean;
import com.yzs.imageshowpickerview.ImageShowPickerListener;
import com.yzs.imageshowpickerview.ImageShowPickerView;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * Created by 泅渡者
 * Created on 2017/5/18.
 * 儿童预检记录
 */

public class ChildpictureFragment extends BaseFragment<ChildpictureContract.Presenter> implements ChildpictureContract.View {

    @Bind(R.id.cb1)
    CheckBox cb1;
    @Bind(R.id.cb2)
    CheckBox cb2;
    @Bind(R.id.cb3)
    CheckBox cb3;
    @Bind(R.id.cb4)
    CheckBox cb4;
    @Bind(R.id.cb5)
    CheckBox cb5;
    @Bind(R.id.cb6)
    CheckBox cb6;
    @Bind(R.id.cb7)
    CheckBox cb7;
    @Bind(R.id.cb8)
    CheckBox cb8;
    @Bind(R.id.cb9)
    CheckBox cb9;
    @Bind(R.id.cb10)
    CheckBox cb10;
    @Bind(R.id.cb11)
    CheckBox cb11;
    @Bind(R.id.cb12)
    CheckBox cb12;
    @Bind(R.id.cb13)
    CheckBox cb13;
    @Bind(R.id.it_picker_view)
    ImageShowPickerView pickerView;
    @Bind(R.id.btn_save)
    Button btn_save;

    SearchResBean searchResBean;
    //存储
    public static final int REQUEST_CODE_PERMISSION_STORAGE = 100;
    //相机
    public static final int REQUEST_CODE_PERMISSION_CAMERA = 101;


    private List<ImageBean> list;


    @Override
    public int onSetLayoutId() {
        return R.layout.fragment_picture;
    }

    @Override
    public void initView() {
        this.createPresenter(new ChildpicturePresenter(this, getActivity()));
        Gson gson = new Gson();
        searchResBean = gson.fromJson(getActivity().getIntent().getStringExtra("SearchResBean").toString(), new TypeToken<SearchResBean>() {
        }.getType());

        CheckBox[] cbList = {cb1, cb2, cb3, cb4, cb5, cb6, cb7, cb8, cb9, cb10, cb11, cb12, cb13};//监护人信息集合

        RecordInfo recordInfo = new RecordInfo();
        recordInfo.setServiceId("phis.mobileService");
        recordInfo.setMethod("execute");
        recordInfo.setServiceAction("getPhotoData");
        RecordInfo.BodyBean bodyBean = new RecordInfo.BodyBean();
        bodyBean.setEMPIID(searchResBean.getBody().getEMPIID());
        recordInfo.setBody(bodyBean);
        presenter.getPhotoInfo(recordInfo);

        list = new ArrayList<>();


        Log.e("list", "======" + list.size());
        pickerView.setImageLoaderInterface(new Loader());
        pickerView.setNewData(list);
        //展示有动画和无动画

        pickerView.setShowAnim(true);
        pickerView.setMaxNum(2);
        pickerView.setmPicSize(200);
        pickerView.setShowAnim(true);
        pickerView.setPickerListener(new ImageShowPickerListener() {
            @Override
            public void addOnClickListener(int remainNum) {

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    checkPermission(REQUEST_CODE_PERMISSION_CAMERA);
                } else {
                    final TakePhotosDialog dialog = new TakePhotosDialog(getActivity(), R.style.dialog_setting);//设置dialog的样式
                    Window window = dialog.getWindow();
                    window.setGravity(Gravity.BOTTOM);
                    window.setWindowAnimations(R.style.dialog_animation); // 添加动画
                    dialog.show();
                    WindowManager windowManager = getActivity().getWindowManager();
                    Display display = windowManager.getDefaultDisplay();
                    WindowManager.LayoutParams params = dialog.getWindow().getAttributes();
                    params.width = (int) (display.getWidth());
                    dialog.getWindow().setAttributes(params);
                    Button choose_picture = (Button) dialog.findViewById(R.id.bt_choose_picture);
                    Button take_picture = (Button) dialog.findViewById(R.id.bt_take_picture);
                    Button cancel = (Button) dialog.findViewById(R.id.bt_cancel);
                    take_picture.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            CropImageUtils.getInstance().takePhoto(ChildpictureFragment.this.getActivity());
                            dialog.dismiss();
                        }
                    });
                    choose_picture.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            CropImageUtils.getInstance().openAlbum(ChildpictureFragment.this.getActivity());
                            dialog.dismiss();
                        }
                    });
                    cancel.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            dialog.dismiss();
                        }
                    });
                }

            }

            @Override
            public void picOnClickListener(List<ImageShowPickerBean> list, int position, int remainNum) {
            }

            @Override
            public void delOnClickListener(int position, int remainNum) {

            }
        });
        pickerView.show();

        presenter.guardianChange(cbList);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        CropImageUtils.getInstance().onActivityResult(getActivity(), requestCode, resultCode, data, new CropImageUtils.OnResultListener() {
            @Override
            public void takePhotoFinish(String path) {
                if (TextUtils.isEmpty(path)) {
                    return;
                } else {
                    presenter.toUpload(path);
                }

            }

            @Override
            public void selectPictureFinish(String path) {
                ToastUtils.showShort("打开图片：" + path);
                if (TextUtils.isEmpty(path)) {
                    return;
                } else {
                    presenter.toUpload(path);
                }
            }

            @Override
            public void cropPictureFinish(String path) {


            }
        });
    }

    /**
     * 检测权限
     */
    public void checkPermission(int permissionType) {
        if (Build.VERSION.SDK_INT >= 23) {
            switch (permissionType) {
                //调用单个权限
                case REQUEST_CODE_PERMISSION_STORAGE:
                    AndPermission.with(this)
                            .requestCode(REQUEST_CODE_PERMISSION_STORAGE)
                            .permission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                            .send();
                    break;
                //调用多个权限，相机和存储
                case REQUEST_CODE_PERMISSION_CAMERA:
                    //如果没有申请权限
                    if (!AndPermission.hasPermission(getActivity(), Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                        AndPermission.with(this)
                                .requestCode(REQUEST_CODE_PERMISSION_CAMERA)
                                .permission(Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE)
                                .send();
                    } else {
                        final TakePhotosDialog dialog = new TakePhotosDialog(getActivity(), R.style.dialog_setting);//设置dialog的样式
                        Window window = dialog.getWindow();
                        window.setGravity(Gravity.BOTTOM);
                        window.setWindowAnimations(R.style.dialog_animation); // 添加动画
                        dialog.show();
                        WindowManager windowManager = getActivity().getWindowManager();
                        Display display = windowManager.getDefaultDisplay();
                        WindowManager.LayoutParams params = dialog.getWindow().getAttributes();
                        params.width = (int) (display.getWidth());
                        dialog.getWindow().setAttributes(params);
                        Button choose_picture = (Button) dialog.findViewById(R.id.bt_choose_picture);
                        Button take_picture = (Button) dialog.findViewById(R.id.bt_take_picture);
                        Button cancel = (Button) dialog.findViewById(R.id.bt_cancel);
                        take_picture.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                CropImageUtils.getInstance().takePhoto(ChildpictureFragment.this.getActivity());
                                dialog.dismiss();
                            }
                        });
                        choose_picture.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                CropImageUtils.getInstance().openAlbum(ChildpictureFragment.this.getActivity());
                                dialog.dismiss();
                            }
                        });
                        cancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                dialog.dismiss();
                            }
                        });
                    }
                    break;
            }
        }
    }

    /**
     * 动态权限回调
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case REQUEST_CODE_PERMISSION_STORAGE:
                //就用直接一句话搞定
                AndPermission.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
                break;
            case REQUEST_CODE_PERMISSION_CAMERA:
                //自定义Dialog
                AndPermission.onRequestPermissionsResult(requestCode, permissions, grantResults, new PermissionListener() {
                    @Override
                    public void onSucceed(int requestCode, List<String> grantPermissions) {
                        CropImageUtils.getInstance().takePhoto(getActivity());
                    }

                    @Override
                    public void onFailed(int requestCode, List<String> deniedPermissions) {
                        // 用户否勾选了不再提示并且拒绝了权限，那么提示用户到设置中授权。
                        if (AndPermission.hasAlwaysDeniedPermission(getActivity(), deniedPermissions)) {
                            AndPermission.defaultSettingDialog(getActivity(), REQUEST_CODE_PERMISSION_CAMERA)
                                    .setTitle(getString(R.string.permission_request_error))
                                    .setMessage(getString(R.string.permission_avatar))
                                    .setNegativeButton(getString(R.string.cancel_value), new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            getActivity().finish();
                                        }
                                    })
                                    .show();
                        }
                    }
                });
                break;
        }
    }

    @OnClick(R.id.btn_save)
    public void onViewClicked() {
        String str = presenter.getStr();
        PicSaveInfoBean picSaveInfoBean = new PicSaveInfoBean();
        picSaveInfoBean.setMethod("execute");
        picSaveInfoBean.setServiceAction("saveData");
        picSaveInfoBean.setServiceId("phis.mobileService");
        PicSaveInfoBean.BodyBean bodyBean = new PicSaveInfoBean.BodyBean();
        bodyBean.setEMPIID(searchResBean.getBody().getEMPIID());

        if (pickerView.getDataList().size() == 0) {

        } else if (pickerView.getDataList().size() == 1) {
            ImageBean imageBean = (ImageBean) pickerView.getDataList().get(0);
            bodyBean.setIMAGEPATH1(imageBean.getWebPath());
        } else {
            ImageBean imageBean = (ImageBean) pickerView.getDataList().get(0);
            bodyBean.setIMAGEPATH1(imageBean.getWebPath());
            ImageBean imageBean2 = (ImageBean) pickerView.getDataList().get(1);
            bodyBean.setIMAGEPATH2(imageBean2.getWebPath());
        }
        bodyBean.setCONTACTID((String) SpUtils.get(this.getActivity(), "UserName", ""));
        bodyBean.setRELATIVE(str);
        picSaveInfoBean.setBody(bodyBean);
        presenter.toSave(picSaveInfoBean);

    }

    @Override
    public void hideLoading() {
        if (customProgress != null) {
            customProgress.dismiss();
        }
    }

    @Override
    public void showLoadingDialog() {
        customProgress = CustomProgress.show(getActivity(), "正在上传...", true, null);
    }


    @Override
    public void showUrl(PicResBean str) {
        List<ImageBean> list = new ArrayList<>();
        list.add(new ImageBean(str.getBody().getWebPath(), MyApplication.getInstance().getBase_url() + str.getBody().getWebPath()));
        pickerView.addData(list);
    }

    /**
     * 展示初始信息
     */
    @Override
    public void ShowPhotoinfo(PhotoResBean photoResBean) {
        if (photoResBean == null) return;
        String str = photoResBean.getBody().getRELATIVE();
        if (!TextUtils.isEmpty(str)) {
            String[] a = str.split("\\,");
            for (String s : a) {
                switch (s) {
                    case "父亲":
                        cb1.setChecked(true);
                        break;
                    case "母亲":
                        cb7.setChecked(true);
                        break;
                    case "祖父":
                        cb2.setChecked(true);
                        break;
                    case "祖母":
                        cb8.setChecked(true);
                        break;
                    case "外祖父":
                        cb3.setChecked(true);
                        break;
                    case "外祖母":
                        cb9.setChecked(true);
                        break;
                    case "叔父":
                        cb4.setChecked(true);
                        break;
                    case "姑母":
                        cb10.setChecked(true);
                        break;
                    case "舅父":
                        cb5.setChecked(true);
                        break;
                    case "姨母":
                        cb11.setChecked(true);
                        break;
                    case "兄弟":
                        cb6.setChecked(true);
                        break;
                    case "姐妹":
                        cb12.setChecked(true);
                        break;
                    case "其他":
                        cb13.setChecked(true);
                        break;
                }
            }
        }
        List<ImageBean> list = new ArrayList<>();

        if (!TextUtils.isEmpty(photoResBean.getBody().getIMAGEPATH1())) {

            list.add(new ImageBean(
                    photoResBean.getBody().getIMAGEPATH1(), MyApplication.getInstance().getBase_url() + photoResBean.getBody().getIMAGEPATH1()));

        }
        if (!TextUtils.isEmpty(photoResBean.getBody().getIMAGEPATH2())) {

            list.add(new ImageBean(
                    photoResBean.getBody().getIMAGEPATH2(), MyApplication.getInstance().getBase_url() + photoResBean.getBody().getIMAGEPATH2()));

        }
        pickerView.addData(list);

    }

}
